from fastapi import APIRouter, Depends, HTTPException, status
from app.schemas.schemas import User, ChangePasswordRequest
from app.models import models
from app.dependencies import get_current_user, get_current_active_user
from fastapi.responses import JSONResponse
from app.security.security import get_password_hash, verify_password
from app.db import crud
from sqlalchemy.orm import Session
from app.db.db import get_db
from fastapi.responses import Response  # Changed from JSONResponse

router = APIRouter(tags=["auth"])


@router.get("/users/me", response_model=User)
async def read_users_me(current_user: models.DUser = Depends(get_current_active_user)):

    return User.model_validate(current_user)


# 修改密码
@router.put("/users/me/password")
async def update_users_me_password(
    request: ChangePasswordRequest,
    current_user: models.DUser = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):

    # 1. 验证当前密码
    if not verify_password(request.current_password, current_user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Current password is incorrect",
        )

    # 2. 检查新密码一致性
    if request.new_password != request.confirm_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="New password and confirmation do not match",
        )

    # 3. 检查新密码和旧密码是否相同
    if request.new_password == request.current_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="New password is the same as current password",
        )

    # 4. 更新密码
    crud.update_user_password(
        db=db, user_id=current_user.id, new_password=request.new_password
    )
    return Response()
